package com.hrms.web.sys_user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hrms.web.sys_menu.entity.AssignTreeParm;
import com.hrms.web.sys_menu.entity.AssignTreeVo;
import com.hrms.web.sys_menu.entity.MakeMenuTree;
import com.hrms.web.sys_menu.entity.SysMenu;
import com.hrms.web.sys_menu.service.SysMenuService;
import com.hrms.web.sys_user.entity.SysUser;
import com.hrms.web.sys_user.mapper.SysUserMapper;
import com.hrms.web.sys_user.service.SysUserService;
import com.hrms.web.sys_user_role.entity.SysUserRole;
import com.hrms.web.sys_user_role.mapper.SysUserRoleMapper;
import com.hrms.web.sys_user_role.service.SysUserRoleService;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @Title: SysUserServiceImpl
 * @Author zhanji
 * @Package com.hrms.web.sys_user.service.impl
 * @description:
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Resource
    private SysUserRoleService sysUserRoleService;

    @Resource
    private SysMenuService sysMenuService;

    //新增用户并添加角色信息
    @Transactional
    @Override
    public void saveUser(SysUser sysUser) {
        //插入用户信息
        int i = this.baseMapper.insert(sysUser);
        //设置用户的角色
        if(i>0){
            //把前端逗号分割的字符串转为数组
            String[] split = sysUser.getRoleId().split(",");
            if(split.length>0){
                List<SysUserRole> roles = new ArrayList<>();
                for(String roleId:split){
                    SysUserRole sysUserRole = new SysUserRole();
                    sysUserRole.setUserId(sysUser.getUserId());
                    sysUserRole.setRoleId(Long.parseLong(roleId));
                    roles.add(sysUserRole);
                }
                //保存到用户角色表
                sysUserRoleService.saveBatch(roles);
            }
        }
    }

    //编辑用户并修改角色信息
    @Transactional
    @Override
    public void editUser(SysUser sysUser) {
        //插入用户信息
        int i = this.baseMapper.updateById(sysUser);
        //设置用户的角色
        if(i>0){
            //把前端逗号分割的字符串转为数组
            String[] split = sysUser.getRoleId().split(",");
            //删除用户原来的角色信息
            QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(SysUserRole::getUserId, sysUser.getUserId());
            sysUserRoleService.remove(queryWrapper);
            //重新插入角色信息
            if(split.length>0){
                List<SysUserRole> roles = new ArrayList<>();
                for(String roleId:split){
                    SysUserRole sysUserRole = new SysUserRole();
                    sysUserRole.setUserId(sysUser.getUserId());
                    sysUserRole.setRoleId(Long.parseLong(roleId));
                    roles.add(sysUserRole);
                }
                //保存到用户角色表
                sysUserRoleService.saveBatch(roles);
            }
        }
    }

    @Override
    @Transactional
    public void deleteUser(Long userId) {
        //删除用户
        int i = this.baseMapper.deleteById(userId);
        if(i>0){
            //删除角色
            QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(SysUserRole::getUserId, userId);
            sysUserRoleService.remove(queryWrapper);
        }
    }

    @Override
    public AssignTreeVo getAssignTree(AssignTreeParm parm) {
        //查询用户的信息
        SysUser user = this.baseMapper.selectById(parm.getUserId());
        List<SysMenu> menuList =null;
        //判断是否是超级管理员
        if (StringUtils.isNotEmpty(user.getIsAdmin()) && "1".equals(user.getIsAdmin())) {
            //是超级管理员，查询所有的菜单
            menuList =sysMenuService.list();
        }else {
            menuList =sysMenuService.selectMenuByUserId(parm.getUserId());
        }
        //组装树
        List<SysMenu> makeTree = MakeMenuTree.makeTree(menuList, 0L);
        //查询角色原来的菜单
        List<SysMenu> menubyRole = sysMenuService.selectMenuByRoleId(parm.getRoleId());
        List<Long> ids = new ArrayList<>();
        Optional.ofNullable(menubyRole).orElse(new ArrayList<>())
            .stream()
            .filter(item ->item!=null)
            .forEach(item->{
                ids.add(item.getMenuId());
            });
        //组装返回的数据
        AssignTreeVo vo =new AssignTreeVo();
        vo.setCheckList(ids.toArray());
        vo.setMenuList(makeTree);
        return vo;
    }

    @Override
    public SysUser loadUser(String username) {
        QueryWrapper<SysUser> query =new QueryWrapper<>();
        query.lambda().eq(SysUser::getUsername, username);
        //根据用户名查询
        SysUser user = this.baseMapper.selectOne(query);
        return user;
    }
}
